package com.example.xmltohtml.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import javax.servlet.http.HttpServletRequest;

//import cn.edu.scu.util.executeCmd.ExecuteCmd;

public class ToHTML {
	/***
	 * 
	 * @param attachmentPath   待转换pdf相对路径(注：路径中不能有空格)
	 * @param request
	 * @return atttachmentURL 转换后html的相对路径
	 * @throws Exception
	 */
	public static String pdfToHtml(String attachmentPath, String htmlPath,HttpServletRequest request)
			throws Exception {
//		attachmentPath = request.getSession().getServletContext()
//				.getRealPath("/") + attachmentPath;
		attachmentPath = attachmentPath.replaceAll("\\\\", "/");
		String pdfDirname = attachmentPath.substring(0, attachmentPath.lastIndexOf("/"));
		String pdfFilename = attachmentPath.substring(attachmentPath.lastIndexOf("/") + 1,
				attachmentPath.lastIndexOf("."));
		int lastIndex = attachmentPath.lastIndexOf(".");
		String htmlDirName = pdfDirname + "/html/";
		File htmlDir = new File(htmlDirName);
		if(!htmlDir.exists()){
			htmlDir.mkdirs();
		}
		// 得到文件后缀名
		String suffix = attachmentPath.substring(lastIndex);
		StringBuilder sb= new StringBuilder();
		if (suffix.equals(".pdf")) {			 
			 sb.append("cmd /c d:/pdf2htmlEX/");
			 sb.append("pdf2htmlEX ");
			 sb.append(attachmentPath);
			 sb.append(" ");
			sb.append("--dest-dir ");
			 sb.append(htmlPath);			 
		}
		System.out.println(sb.toString());
		String attachmentURL = pdfDirname + "/html/" + pdfFilename+ ".html";
		attachmentURL = attachmentURL.substring(attachmentURL.indexOf("/upload/") + 1,
						attachmentURL.length());
		try {
            Process process = Runtime.getRuntime().exec(sb.toString());
            if (process.waitFor() == 0) {// 0 表示线程正常终止。
            	System.out.println("pdf->html转换完毕！");
            }else{
            	System.out.println("pdf->html转换失败！");
            	attachmentURL =  null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
		return attachmentURL;
	}
	
	/**
	 * 调用pdf2htmlEX将pdf文件转换为html文件,该方法处理了Runtime.exec()一直阻塞的情况，而上面方法没有
	 * @param command 调用exe的字符串
	 * @param pdfPath 需要转换的pdf文件名称 (注：路径中不能有空格)
	 * @param htmlDir 生成的html文件名称(注：html保存目录中路径分隔符必须是右斜杠"\"，左斜杠"/"不行)
	 * @return  转换成功则返回true，失败则返回false
	 */
	public static boolean pdf2html(String pdfPath,String htmlDir){
		htmlDir = htmlDir.replaceAll( "/","\\\\");
		String command = "cmd /c d:/project/pdf2htmlEX/pdf2htmlEX --dest-dir";
		command = command +" "+htmlDir+" "+pdfPath;
		System.out.println(command);
//		if(ExecuteCmd.execute(command)){
//			System.out.println("pdf->html转换完毕！");
//			return true;
//		}else{
//			System.out.println("pdf->html转换失败！");
//			return false;
//		}
		return false;
	}
	
	/**
	 * 调用resources/exe目录下的pdf2htmlEX.exe将PDF转换为HTML
	 * @param pdfFileName resources/pdf目录下的PDF文件名（如：test.pdf）
	 * @param htmlOutputPath 输出HTML文件的完整路径（如：output/test.html）
	 * @return 转换成功返回true，失败返回false
	 */
	public static boolean pdf2htmlFromResources(String pdfFileName, String htmlOutputPath) {
		try {
			// 1. 创建临时目录
			Path tempDir = Files.createTempDirectory("pdf2html");
			Path exeTempPath = tempDir.resolve("pdf2htmlEX.exe");
			Path pdfTempPath = tempDir.resolve(pdfFileName);
			
			// 2. 复制exe到临时目录
			try (InputStream exeStream = ToHTML.class.getClassLoader()
					.getResourceAsStream("exe/pdf2htmlEX.exe")) {
				if (exeStream == null) {
					throw new IOException("找不到 resources/exe/pdf2htmlEX.exe");
				}
				Files.copy(exeStream, exeTempPath, StandardCopyOption.REPLACE_EXISTING);
			}
			
			// 3. 复制PDF到临时目录
			try (InputStream pdfStream = ToHTML.class.getClassLoader()
					.getResourceAsStream("pdf/" + pdfFileName)) {
				if (pdfStream == null) {
					throw new IOException("找不到 resources/pdf/" + pdfFileName);
				}
				Files.copy(pdfStream, pdfTempPath, StandardCopyOption.REPLACE_EXISTING);
			}
			
			// 4. 确保输出目录存在
			File outputFile = new File(htmlOutputPath);
			File outputDir = outputFile.getParentFile();
			if (outputDir != null && !outputDir.exists()) {
				outputDir.mkdirs();
			}
			
			// 5. 构建命令
			ProcessBuilder pb = new ProcessBuilder(
				exeTempPath.toAbsolutePath().toString(),
				"--dest-dir", outputDir.getAbsolutePath(),
				pdfTempPath.toAbsolutePath().toString(),
				outputFile.getName()
			);
			pb.redirectErrorStream(true);
			
			System.out.println("执行命令: " + String.join(" ", pb.command()));
			
			// 6. 执行转换
			Process process = pb.start();
			
			// 7. 读取输出
			try (java.io.BufferedReader reader = new java.io.BufferedReader(
					new java.io.InputStreamReader(process.getInputStream(), "UTF-8"))) {
				String line;
				while ((line = reader.readLine()) != null) {
					System.out.println(line);
				}
			}
			
			int exitCode = process.waitFor();
			boolean success = exitCode == 0 && outputFile.exists();
			
			// 8. 清理临时文件
			try {
				Files.deleteIfExists(exeTempPath);
				Files.deleteIfExists(pdfTempPath);
				Files.deleteIfExists(tempDir);
			} catch (Exception e) {
				System.err.println("清理临时文件失败: " + e.getMessage());
			}
			
			return success;
			
		} catch (Exception e) {
			System.err.println("PDF转HTML失败: " + e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
  public static void main(String[] args) {
	  try {

		  // 转换 resources/pdf 目录下的 H2_AN202505081669303055_1.pdf
		  boolean success = ToHTML.pdf2htmlFromResources(
				  "H2_AN202505081669303055_1.pdf",
				  "output/converted.html"
		  );
		  String cmd = "cmd /c d:/pdf2htmlEX/pdf2htmlEX --dest-dir";
		  String htmldir = "d:\\apache-tomcat-7.0.55\\webapps\\Foundation\\upload\\reimbursement\\attachment\\20160601\\html";
		  String pdfPath = "d:\\apache-tomcat-7.0.55\\webapps\\Foundation\\upload\\reimbursement\\attachment\\20160601\\a5f79db0-27cd-4be8-9531-33de8a960ac9.pdf";
				  //"D:\\apache-tomcat-7.0.55\\webapps\\Foundation\\upload\\reimbursement\\attachment\\20160512\\";
		//pdfToHtml(dir+"75612a74-cf6b-4cce-a52d-689857adc5e3.pdf",dir+"html",null);
		  System.out.println(pdf2html(pdfPath,htmldir));
	} catch (Exception e) {
		e.printStackTrace();
	} 
  }
}
